/**
 * 树节点查询插件，依赖Ext.ux.form.SearchField
 * 
 * @param {} config
 * @author Wuqingming
 * @version 1.0
 * @since 2011-07-04
 */
Ext.namespace('Ext.ux.tree');
Ext.ux.tree.TreeSearch = function(config) {
	Ext.apply(this, config);
	this.width 			= config.width || 160;					//宽度
	this.searchType		= config.searchType || 'local';			//搜索模式, local|remote
	this.insertPosition	= config.insertPosition || 'pre';		//插入位置, pre|last
};

Ext.extend(Ext.ux.tree.TreeSearch, Ext.util.Observable, {
	
	init: function(treePanel){
		this.treePanel = treePanel;
		treePanel.on('render', this.onRender, this);
	},
	//private
	onRender : function() {
		this.searchField = new Ext.ux.form.SearchField({
			id : this.treePanel.id + 'treeNodeSearchField',
			width : this.width,
			emptyText : '查询树节点',
			trigger2ClickHandlerScope : this
		});
		var scope = this;
		this.loadStatus = 'wait';
		this.searchField.onTrigger2Click = function () {
			if (scope.searchType == 'local') {			//本地
				scope.filterNodeByText(scope.searchField.getValue());
			} else if (scope.searchType == 'remote') {	//远程，重新加载
				var treeLoader = scope.treePanel.getLoader();
				treeLoader.on("beforeload", function(treeLoader, node) {
			        treeLoader.baseParams.nodeText = scope.searchField.getValue();
			    });
			    if (scope.loadStatus == 'wait' && !scope.checkAllNodeLoaded()) {
			    	scope.loadStatus = 'loading';
			    	scope.searchField.disable();
				    treeLoader.load(scope.treePanel.root, function () {
				    	scope.filterNodeByText(scope.searchField.getValue());
				    	scope.loadStatus = 'loaded'
			    		scope.searchField.enable();
				    });
			    } else {
			    	scope.filterNodeByText(scope.searchField.getValue());
			    }
			}
		};
		var toolbar 	= this.treePanel.getTopToolbar();
		/**
		var items		= toolbar.items;
		if (items != null && items.getCount() > 0 && this.insertPosition == 'pre') {
			items.insert(1, this.treePanel.id + 'treeNodeSearchField', this.searchField);
			items.insert(2, this.treePanel.id + '-', '');
			return;
		}
		*/
		toolbar.add('-');
		toolbar.add(this.searchField);
	},
	
	/** 
     * 展开所有的节点
     */
    expandNodeAll : function(node, index) {
        var scope = this;
        node.expand(true);
        var childs = node.childNodes;
        for (var i = 0; i < childs.length; i++) {
            scope.expandNodeAll(childs[i], (index+1));
        }
    },
    
    /**
     * 判断节点是否已展开
     * @param {} node
     * @return {Boolean}
     */
    checkNodeExpanded : function (node) {
    	if (!node.isLeaf() && !node.isExpanded()) {
    		return false;
    	}
    	if (!node.hasChildNodes()) {
    		return true;
    	}
    	var childNodes	= node.childNodes;
    	for (var i = 0; i < childNodes.length; i++) {
    		if (!this.checkNodeExpanded(childNodes[i])) {
    			return false;
    		}
    	}
    	return true;
    },
    
    /**
     * 判断所有节点是否已展开
     * @return {}
     */
    checkAllNodeExpanded : function () {
    	var root = this.treePanel.root;
    	return this.checkNodeExpanded(root);
    },
    
    /**
     * 判断节点是否已加载完毕
     * @param {} node
     * @return {Boolean}
     */
    checkNodeLoaded : function (node) {
    	if (!node.isLeaf() && !node.isLoaded()) {
    		return false;
    	}
    	if (!node.hasChildNodes()) {
    		return true;
    	}
    	var childNodes	= node.childNodes;
    	for (var i = 0; i < childNodes.length; i++) {
    		if (!this.checkNodeLoaded(childNodes[i])) {
    			return false;
    		}
    	}
    	return true;
    },
    
    /**
     * 判断所有节点是否已加载完毕
     * @return {}
     */
    checkAllNodeLoaded : function () {
    	var root = this.treePanel.root;
    	return this.checkNodeLoaded(root);
    },
              
	/**
	 * 过滤显示节点
	 * 
	 * @param {} text
	 */
	filterNodeByText : function(text) {
		var scope = this;
		if (this[this.id + 'filterNode'] == null) {
			this[this.id + 'filterNode'] = new Ext.tree.TreeFilter(
				this.treePanel, {
				clearBlank : true,
				autoClear : true
			});
		}
		var filter = this[this.id + 'filterNode'];
		this.treePanel.expandAll();
		scope.filterBy(filter, text);
	},
	
	filterBy : function (filter, text) {
		var scope 	= this;
		var root 	= scope.treePanel.root;
		var waitFilterFlag = false;
		if (root instanceof Ext.tree.AsyncTreeNode) {
			if (!scope.checkAllNodeLoaded()) {
				waitFilterFlag = true;
			}
		} else {
			if (!this.checkAllNodeExpanded()) {
				waitFilterFlag = true;
			}
		}
		if (waitFilterFlag && scope.filterTask == null) {
			scope.filterTask = {
			    run: function(){
			        scope.filterBy(filter, text);
			    },
			    interval: 1000 //1 second
			}
			if (scope.taskRunner == null) {
				scope.taskRunner = new Ext.util.TaskRunner();
			}
			scope.taskRunner.start(scope.filterTask);
		}
		if (waitFilterFlag) {
			return false;
		}
		if (scope.taskRunner) {	//停止等待任务
			scope.taskRunner.stop(scope.filterTask);
		}
		filter.filterBy(function(n) {
			if (text == null) {
				return true;
			}
			if (text == "") {
				return true;
			}
			var str = n.attributes.text;
			var re = new RegExp('^' + Ext.escapeRe(text), 'i');	//关键的代码
			if (re.test(str)) {
				return n;
			}
			if (n.childNodes != null && n.childNodes.length > 0) {
				return scope.filterParse(n, text);
			} else {
				return false;
			}
		});
	},

	/**
	 * 该方法必须配合 Ext.tree.TreeFilter 组件使用 递归过滤解析 like 匹配 如果所有子及无限级下级的子
	 * 没有匹配则返回false
	 * 
	 * @return 返回
	 */
	filterParse : function(node, text) {
		var str = node.attributes.text;
		var re = new RegExp('^' + Ext.escapeRe(text), 'i');	//关键的代码
		if (re.test(str)) {
			return node;
		}
		var nodes = node.childNodes;
		if (nodes == null) {
			return false;
		}
		var tNode = null;
		for (var i = 0; i < nodes.length; i++) {
			if ((tNode = this.filterParse(nodes[i], text))) {
				return tNode;
			}
		}
		return false;
	}
});